
// orderlist.js
var sliderWidth = 96; // 需要设置slider的宽度，用于计算中间位置
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: ["已完成订单", "未完成订单"],
    activeIndex: app.activeIndex,
    sliderOffset: 0,
    sliderLeft: 0,
    undoneorder: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.showLoadings();
    try {
      var that = this;
      // nav选项卡
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            // sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
            sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
          });
        }
      });
    } catch (err) { }

  },

  tabClick: function (e) {
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id,
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    try {
      if (!app.accesstoken) {
        this.setData({
          ModalSwitch: true
        })
        this.GetUserToken();
      }else{
        this.setData({
          ModalSwitch: false
        })
        this.myOrder();
      }
    } catch (err) { }

  },
  processDate(orderMain) {
    var time = orderMain.StartDate.substring(6, 19),
      d = new Date(parseInt(time)),
      m = (d.getMonth() + 1) < 10 ? '0' + (d.getMonth() + 1) : (d.getMonth() + 1),
      day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate(),
      date = d.getFullYear() + '-' + m + '-' + day,
      time = d.getHours() + ':' + d.getMinutes();
    return orderMain.StartDate = date;
  },

  // 获取用户token===========================================
  // 调用微信用户信息接口
  userLogin: function () {
    let that = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          that.codes = res.code;
        }
      },
      fail: function () { }
    })
  },
  // 获取Token，如果用户授权，直接调用微信官方WX.getUserInfo方法获取用户信息，而不是弹框授权
  GetUserToken: function () {
    var that = this;
    // 通过 wx.getSetting 先查询一下用户是否授权了 "scope.record"
    try {
      wx.getSetting({
        success(res) {
          if (res.authSetting['scope.userInfo']) {
            wx.login({
              success: function (res) {
                if (res.code) {
                  // 用户首次进入小程序时，如果检测到用户已经授权，则获取新的Token
                  wx.getUserInfo({
                    success(data) {
                      app.userinfo.nickname = data.userInfo.nickName ? data.userInfo.nickName : '';
                      app.userinfo.headimg = data.userInfo.avatarUrl;
                      that.putUserData(res.code, data.iv, data.encryptedData);
                      that.setData({
                        ModalSwitch: false
                      })
                    }
                  });
                }
              },
              fail: function (err) { }
            })
          } else {
            // 未授权的解决方案 ====  调用微信获取用户信息按钮
            that.userLogin();
            app.hideLoadings();
            that.setData({
              // 页面模态框开关
              // shouquanModal: true,
              // JS模态框开关
              ModalSwitch: true,
            })
          }
        },
        complete: () => {
          app.hideLoadings();
        }
      })
    } catch (err) { }
  },

  // 授权失败模态提示框
  shouquanFail: function () {
    wx.showModal({
      title: '授权失败',
      content: '服务器繁忙，请点击页面按钮重试',
      showCancel: false,
      success: function () {
        app.hideLoadings();
      }
    })
  },
  // 发送用户数据给后台
  putUserData: function (code, IV, EncryptedData) {
    let that = this;
    // Token数据请求
    wx.request({
      url: app.serviceurl + 'GetToken',
      method: "POST",
      data: {
        code: code,
        options: JSON.stringify(app.o),
        IV: IV,
        EncryptedData: EncryptedData
      },
      dataType: 'json',
      success: function (res) {
        if (res.data.AccessToken) {
          that.setData({
            // shouquanModal: false,
            ModalSwitch: false
          })
          let resData = res.data;
          if (resData.openId !== "") {
            app.optionsToken = resData.openId;
          }
          app.HandsetNumber = resData.HandsetNumber;
          app.IsRegister = resData.IsRegister;
          app.newUser = resData.IsNewUser;
          app.accesstoken = resData.AccessToken;
          // 是否为新用户
          app.IsFresh = resData.IsFresh;
          try {
            // 将用户数据存储进本地缓存
            wx.setStorage({
              key: '_userToken',
              data: {
                HandsetNumber: resData.HandsetNumber,
                IsRegister: resData.IsRegister,
                accesstoken: resData.AccessToken,
                userDate: new Date()
              },
            })
            that.myOrder();
            // that.checkfrom(that.op)
          } catch (err) { }
        } else {
          that.shouquanFail();
        }
      },
      fail: function () {
        try {
          that.shouquanFail();
        } catch (e) { }
      },
      complete: () => {
        app.hideLoadings();
      }
    })
  },
  // 用户信息授权按钮  
  bindGetUserInfo(e) {
    try {
      let that = this;
      var user = e.detail;
      app.userinfo.nickname = user.userInfo.nickName ? user.userInfo.nickName : '';
      app.userinfo.headimg = user.userInfo.avatarUrl;
      that.putUserData(this.codes, user.iv, user.encryptedData);
    } catch (err) { }
  },








  // token获取结束===========================================

  myOrder: function () {
    try {
      // 如果token失效（解决从微信推送消息中进入订单列表页面token可能失效的情况）
      // 
      // 
      // 
      // 
      
      let getToken = app.accesstoken ? app.accesstoken : app.stanToken;
      var that = this,
        doneorder = [],
        i,
        undoneorder = [];
      wx.request({
        url: app.serviceurl + 'Order/GetMyOrdersAll/',
        header: {
          Authorization: "Bearer " + getToken
        },
        dataType: 'json',
        success: function (res) {
          var allorder = res.data.Orders;
          if (!res.data.Result) {
            that.setData({
              doneorder: doneorder,
              undoneorder: undoneorder
            })
            return
          };

          if (allorder != null && typeof (allorder) != 'undefined') {
            for (i = 0; i < allorder.length; i++) {
              that.processDate(allorder[i]);
              if (allorder[i].IsFinished == true) {
                doneorder.push(allorder[i])
              } else if (allorder[i].IsFinished == false) {
                undoneorder.push(allorder[i])
              }
            }
          }
          that.setData({
            doneorder: doneorder,
            undoneorder: undoneorder
          })
        },
        fail: function (error) {
          that.setData({
            doneorder: doneorder,
            undoneorder: undoneorder
          })
        },
        complete: function(){
          app.hideLoadings();
        }
      })
    } catch (err) { }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
// 跳转到新版小程序
newEdition:function(){
  wx.navigateToMiniProgram({
    appId: 'wx5c41c321ceb5c552',
    path: 'pages/carpool/book/book',
    envVersion: 'release',
  })
},
  busDetails: function (e) {
    var orderId = e.currentTarget.dataset.id;
    app.orderId = orderId;
    var orderState = e.currentTarget.dataset.orderstate;
    wx.navigateTo({
      url: '/pages/personcenter/orderDetails/orderDetails',
    })
  },
  orderDetails: function (e) {
    var distance = e.currentTarget.dataset.distance;
    var date = e.currentTarget.dataset.startdate;
    var startplace = e.currentTarget.dataset.startplace;
    var endplace = e.currentTarget.dataset.endplace;
    var orderstatus = e.currentTarget.dataset.orderstatus;
    wx.navigateTo({
      url: '/customline/pages/detail/detail?distance=' + distance + '&date=' + date + '&startplace=' + startplace + '&endplace=' + endplace + '&orderstatus=' + orderstatus,
    })
  },
  evalaute: function (e) {
    var startdate = e.currentTarget.dataset.startdate,
      price = e.currentTarget.dataset.price,
      ordercode = e.currentTarget.dataset.ordercode,
      starttime = e.currentTarget.dataset.starttime;
    wx.navigateTo({
      url: '/customline/pages/evalaute/evalaute?startdate=' + startdate + '&price=' + price + '&ordercode=' + ordercode + '&starttime=' + starttime,
    })
  },

  rentDetails: function (e) {
    var ordercode = e.currentTarget.dataset.ordercode;
    var startplace = e.currentTarget.dataset.startplace;
    var endpalce = e.currentTarget.dataset.endpalce;
    var startdate = e.currentTarget.dataset.startdate;
    var starttime = e.currentTarget.dataset.starttime;
    var seatamount = e.currentTarget.dataset.seatamount;
    var issharing = e.currentTarget.dataset.issharing;
    wx.navigateTo({
      url: '/rent/pages/indent/indent?ordercode=' + ordercode + '&startplace=' + startplace + '&endpalce=' + endpalce + '&startdate=' + startdate + '&starttime=' + starttime + '&seatamount=' + seatamount + '&issharing=' + issharing,
    })
  },
  rentevalate: function (e) {
    var startdate = e.currentTarget.dataset.startdate,
      price = e.currentTarget.dataset.price,
      ordercode = e.currentTarget.dataset.ordercode,
      startplace = e.currentTarget.dataset.startplace,
      endplace = e.currentTarget.dataset.endplace,
      starttime = e.currentTarget.dataset.starttime;
    wx.navigateTo({
      url: '/rent/pages/evalaute/evalaute?startdate=' + startdate + '&price=' + price + '&ordercode=' + ordercode + '&starttime=' + starttime + '&startplace=' + startplace + '&endplace=' + endplace,
    })
  }
})